package com.forum.module.system.controller.admin.mail;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.forum.framework.common.pojo.DataResult;
import com.forum.framework.common.util.json.JsonUtils;
import com.forum.module.system.service.mail.MailService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

import static com.forum.framework.common.exception.enums.GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR;
import static com.forum.module.system.enums.ErrorCodeConstants.MAIL_CODE_IS_EXISTS;

/**
 * 功能:
 * 作者:ouyzh
 * 日期:2025/3/18 21:49
 */
@Tag(name = "邮箱接口")
@RestController("mailController")
@RequestMapping("/system/mail")
public class MailController {
    private final MailService mailService;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    public MailController(MailService mailService) {
        this.mailService = mailService;
    }

    /**
     * 获取验证码
     *
     * @param email -
     * @return -
     */
    @Operation(summary = "获取验证码")
    @GetMapping("/code")
    public DataResult<?> sendMail(@RequestParam("email") String email, HttpServletRequest request) {
        // key 邮箱号  value 验证码
        String code = (String) redisTemplate.opsForValue().get(email);

        // 从redis获取验证码，如果获取获取到，提示已经获取验证码，请稍后再获取
        if (!StrUtil.isEmpty(code)) {
            return DataResult.error(MAIL_CODE_IS_EXISTS);
        }

        // 如果从redis获取不到，生成新的6位验证码
        code = RandomUtil.randomNumbers(6);

        boolean isSend = mailService.sendMail(email, code);

        if (isSend) {
            // 生成验证码放到redis里面，设置有效时间为5分钟
            redisTemplate.opsForValue().set(email, JsonUtils.toJsonString(code), 5 * 60, TimeUnit.SECONDS);
            return DataResult.success("获取验证码成功，请查看邮箱");
        }

        return DataResult.error(INTERNAL_SERVER_ERROR);
    }
}
